package cn.sitcat.springcloud.controller;

import cn.sitcat.springcloud.entities.Dept;
import cn.sitcat.springcloud.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author hiseico
 * @date 2019/5/6 15:21
 * @desc 使用RestController构建Restful风格后端API接口
 */
@RestController
public class DeptController {
    @Autowired
    private DeptService deptService;
    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping(value = "/dept/add")
    public boolean add(@RequestBody Dept dept) {
        return deptService.add(dept);
    }

    @GetMapping(value = "/dept/get/{id}")
    public Dept get(@PathVariable("id") Long id) {
        return deptService.get(id);
    }

    @RequestMapping(value = "/dept/list", method = RequestMethod.GET)
    public List<Dept> get() {
        return deptService.list();
    }


    @RequestMapping(value = "/dept/discovery", method = RequestMethod.GET)
    public Object discovery() {
        //获取微服务名称列表
        List<String> list = discoveryClient.getServices();
        System.out.println("======"+list);
        //从eureka的所有微服务中找到一个名字为Mmicroservicecloud-dept的微服务，此处的名字与每个微服务application.yml中的对外暴露的微服务名字匹配
        /**
         * spring:
         *   application:
         *     name: microservicecloud-dept #这个名字就是对外暴露的微服务名字
         */
        List<ServiceInstance> instances = discoveryClient.getInstances("microservicecloud-dept");

        for (ServiceInstance element : instances) {
            System.out.println("ServiceId："+element.getServiceId());
            System.out.println("Host："+element.getHost());
            System.out.println("Port："+element.getPort());
            System.out.println("Uri："+element.getUri());
        }
        return this.discoveryClient;

    }
}
